package com.alice.router.mybatis.dao.impl;

import com.alice.mybatis.dao.UserDao;
import com.alice.mybatis.entity.User;
import com.alice.router.mybatis.dao.UserDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserDaoImpl implements UserDao {
    private SqlSessionFactory sqlSessionFactory;


    //注入SqlSessionFactory
    public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
        this. sqlSessionFactory = sqlSessionFactory;
    }


    @Override
    public User findUserById(int id) throws Exception {
        SqlSession session = sqlSessionFactory.openSession();
        User user = null;
        try {
            // 通过sqlsession调用selectOne方法获取一条结果集
            // 参数1：指定定义的statement的id,参数2：指定向statement中传递的参数
            user = session.selectOne("test.findUserById", id);
            System.out.println(user);
        } finally{
            session.close();
        }
        return user;
    }

    @Override
    public List<User> findUserByUsername(String name) throws Exception {
        SqlSession session = sqlSessionFactory.openSession();
        List<User> users = null;
        try {
            users = session.selectList("test.findUsersByName", name);
            System.out.println(users);
        } finally{
            session.close();
        }
        return users;
    }

    @Override
    public void insertUser(User user) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            sqlSession.insert("test.insertUser", user);
            sqlSession.commit();
        } finally{
            sqlSession.close();
        }
    }

    @Override
    public void insertUser1(User user) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            sqlSession.insert("test.insertUser", user);
            sqlSession.commit();
        } finally{
            sqlSession.close();
        }
    }
}
